Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.67% covered (success)
96.67%
116 / 120
50.00% covered (danger)
50.00%
2 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApieServiceProvider
96.67% covered (success)
96.67%
116 / 120
50.00% covered (danger)
50.00%
2 / 4
26
0.00% covered (danger)
0.00%
0 / 1
 autoTagHashmapActions
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
4.00
 boot
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
 register
95.24% covered (success)
95.24%
60 / 63
0.00% covered (danger)
0.00%
0 / 1
14
 sanitizeConfig
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2namespace Apie\LaravelApie;
3
4use Apie\ApieCommonPlugin\ApieCommonPluginServiceProvider;
5use Apie\CmsApiDropdownOption\CmsDropdownServiceProvider;
6use Apie\Common\CommonServiceProvider;
7use Apie\Common\Interfaces\BoundedContextSelection;
8use Apie\Common\Interfaces\DashboardContentFactoryInterface;
9use Apie\Common\Wrappers\BoundedContextHashmapFactory;
10use Apie\Common\Wrappers\ConsoleCommandFactory as CommonConsoleCommandFactory;
11use Apie\Console\ConsoleServiceProvider;
12use Apie\Core\CoreServiceProvider;
13use Apie\Core\Session\CsrfTokenProvider;
14use Apie\DoctrineEntityConverter\DoctrineEntityConverterProvider;
15use Apie\DoctrineEntityDatalayer\Commands\ApieUpdateIdfCommand;
16use Apie\DoctrineEntityDatalayer\DoctrineEntityDatalayerServiceProvider;
17use Apie\DoctrineEntityDatalayer\EntityReindexer;
18use Apie\DoctrineEntityDatalayer\IndexStrategy\BackgroundIndexStrategy;
19use Apie\DoctrineEntityDatalayer\IndexStrategy\DirectIndexStrategy;
20use Apie\DoctrineEntityDatalayer\IndexStrategy\IndexAfterResponseIsSentStrategy;
21use Apie\DoctrineEntityDatalayer\IndexStrategy\IndexStrategyInterface;
22use Apie\Faker\FakerServiceProvider;
23use Apie\HtmlBuilders\ErrorHandler\CmsErrorRenderer;
24use Apie\HtmlBuilders\HtmlBuilderServiceProvider;
25use Apie\LaravelApie\Config\LaravelConfiguration;
26use Apie\LaravelApie\ContextBuilders\CsrfTokenContextBuilder;
27use Apie\LaravelApie\ContextBuilders\RegisterBoundedContextActionContextBuilder;
28use Apie\LaravelApie\ContextBuilders\SessionContextBuilder;
29use Apie\LaravelApie\ErrorHandler\ApieErrorRenderer;
30use Apie\LaravelApie\ErrorHandler\Handler;
31use Apie\LaravelApie\Providers\CmsServiceProvider;
32use Apie\LaravelApie\Providers\SecurityServiceProvider;
33use Apie\LaravelApie\Wrappers\Cms\DashboardContentFactory;
34use Apie\LaravelApie\Wrappers\Core\BoundedContextSelected;
35use Apie\LaravelApie\Wrappers\Queue\BackgroundProcessPersistListener;
36use Apie\Maker\MakerServiceProvider;
37use Apie\RestApi\RestApiServiceProvider;
38use Apie\SchemaGenerator\SchemaGeneratorServiceProvider;
39use Apie\Serializer\SerializerServiceProvider;
40use Apie\ServiceProviderGenerator\TagMap;
41use Illuminate\Config\Repository;
42use Illuminate\Contracts\Debug\ExceptionHandler;
43use Illuminate\Contracts\Events\Dispatcher;
44use Illuminate\Support\ServiceProvider;
45use Psr\EventDispatcher\EventDispatcherInterface;
46use Psr\Http\Message\ServerRequestInterface;
47use Symfony\Component\Config\ConfigCache;
48use Symfony\Component\Config\Definition\Processor;
49use Symfony\Component\Config\Resource\ReflectionClassResource;
50use Symfony\Component\Console\Application;
51use Symfony\Component\EventDispatcher\EventDispatcher;
52
53class ApieServiceProvider extends ServiceProvider
54{
55    /**
56     * @var array<string, array<int, class-string<ServiceProvider>>> $dependencies
57     */
58    private array $dependencies = [
59        'enable_common_plugin' => [
60            ApieCommonPluginServiceProvider::class,
61        ],
62        'enable_cms' => [
63            CommonServiceProvider::class,
64            HtmlBuilderServiceProvider::class, // it's important that this loads before CmsServiceProvider!!!
65            CmsServiceProvider::class,
66            SerializerServiceProvider::class,
67        ],
68        'enable_cms_dropdown' => [
69            CommonServiceProvider::class,
70            CmsDropdownServiceProvider::class,
71        ],
72        'enable_core' => [
73            CoreServiceProvider::class,
74        ],
75        'enable_console' => [
76            CommonServiceProvider::class,
77            ConsoleServiceProvider::class,
78            SerializerServiceProvider::class,
79        ],
80        'enable_doctrine_entity_converter' => [
81            CoreServiceProvider::class,
82            DoctrineEntityConverterProvider::class,
83        ],
84        'enable_doctrine_entity_datalayer' => [
85            CoreServiceProvider::class,
86            DoctrineEntityConverterProvider::class,
87            DoctrineEntityDatalayerServiceProvider::class,
88        ],
89        'enable_security' => [
90            CommonServiceProvider::class,
91            SerializerServiceProvider::class,
92            SecurityServiceProvider::class,
93        ],
94        'enable_rest_api' => [
95            CommonServiceProvider::class,
96            RestApiServiceProvider::class,
97            SchemaGeneratorServiceProvider::class,
98            SerializerServiceProvider::class,
99        ],
100        'enable_faker' => [
101            FakerServiceProvider::class,
102        ],
103        'enable_maker' => [
104            MakerServiceProvider::class,
105        ],
106    ];
107
108    private function autoTagHashmapActions(): void
109    {
110        $boundedContextConfig = config('apie.bounded_contexts');
111        $scanBoundedContextConfig = config('apie.scan_bounded_contexts');
112        $factory = new BoundedContextHashmapFactory(
113            $boundedContextConfig ?? [],
114            $scanBoundedContextConfig ?? [],
115            new EventDispatcher(),
116        );
117        $hashmap = $factory->create();
118        foreach ($hashmap as $boundedContext) {
119            foreach ($boundedContext->actions as $action) {
120                $class = $action->getDeclaringClass();
121                if (!$class->isInstantiable()) {
122                    continue;
123                }
124                $className = $class->name;
125                TagMap::register(
126                    $this->app,
127                    $className,
128                    ['apie.context']
129                );
130            }
131        }
132    }
133
134    public function boot(): void
135    {
136        $this->autoTagHashmapActions();
137        $this->loadViewsFrom(__DIR__ . '/../templates', 'apie');
138        $this->loadRoutesFrom(__DIR__.'/../resources/routes.php');
139        TagMap::registerEvents($this->app);
140
141        if ($this->app->runningInConsole()) {
142            $commands = [];
143            $commands[] = ApieUpdateIdfCommand::class;
144            // for some reason these are not called in integration tests without re-registering them
145            foreach (TagMap::getServiceIdsWithTag($this->app, 'console.command') as $taggedCommand) {
146                $serviceId = 'apie.console.tagged.' . $taggedCommand;
147                $this->app->singleton($serviceId, function () use ($taggedCommand) {
148                    return $this->app->get($taggedCommand);
149                });
150                $commands[] = $serviceId;
151            }
152            /** @var CommonConsoleCommandFactory $factory */
153            $factory = $this->app->get('apie.console.factory');
154            foreach ($factory->create($this->app->get(Application::class)) as $command) {
155                $serviceId = 'apie.console.registered.' . $command->getName();
156                $this->app->instance($serviceId, $command);
157                $commands[] = $serviceId;
158            }
159            $this->commands($commands);
160        }
161    }
162
163    public function register()
164    {
165        $this->mergeConfigFrom(__DIR__ . '/../resources/apie.php', 'apie');
166
167        // add PSR-14 support if needed:
168        if (!$this->app->bound(EventDispatcherInterface::class)) {
169            $this->app->bind(EventDispatcherInterface::class, function () {
170                return new class($this->app->make(Dispatcher::class)) implements EventDispatcherInterface {
171                    public function __construct(private readonly Dispatcher $dispatcher)
172                    {
173                    }
174
175                    public function dispatch(object $event): object
176                    {
177                        $this->dispatcher->dispatch($event);
178                        return $event;
179                    }
180                };
181            });
182        }
183
184        // fix for https://github.com/laravel/framework/issues/30415
185        $this->app->extend(
186            ServerRequestInterface::class,
187            function (ServerRequestInterface $psrRequest) {
188                $route = $this->app->make('request')->route();
189                if ($route) {
190                    $parameters = $route->parameters();
191                    foreach ($parameters as $key => $value) {
192                        $psrRequest = $psrRequest->withAttribute($key, $value);
193                    }
194                }
195                return $psrRequest;
196            }
197        );
198
199        $this->app->bind(IndexStrategyInterface::class, function () {
200            $config = config();
201            if ($config->get('apie.enable_doctrine_entity_datalayer')) {
202                $type = $config->get('apie.doctrine.indexing.type', 'direct');
203                return match ($type) {
204                    'direct' => new DirectIndexStrategy($this->app->get(EntityReindexer::class)),
205                    'late' => new IndexAfterResponseIsSentStrategy($this->app->get(EntityReindexer::class)),
206                    'background' => new BackgroundIndexStrategy(),
207                    default => $this->app->get(config('apie.doctrine.indexing.service', DirectIndexStrategy::class)),
208                };
209            }
210
211            return new DirectIndexStrategy($this->app->get(EntityReindexer::class));
212        });
213
214        $this->app->bind(ApieErrorRenderer::class, function () {
215            return new ApieErrorRenderer(
216                $this->app->bound(CmsErrorRenderer::class) ? $this->app->make(CmsErrorRenderer::class) : null,
217                $this->app->make(\Apie\Common\ErrorHandler\ApiErrorRenderer::class),
218                config('apie.cms.base_url')
219            );
220        });
221
222        $this->app->extend(ExceptionHandler::class, function (ExceptionHandler $service) {
223            return new Handler($this->app, $service);
224        });
225        
226        $this->app->bind(DashboardContentFactoryInterface::class, DashboardContentFactory::class);
227        $this->app->bind(BoundedContextSelection::class, BoundedContextSelected::class);
228
229        $alreadyRegistered = [];
230        foreach ($this->dependencies as $configKey => $dependencies) {
231            if (config('apie.' . $configKey, false)) {
232                foreach ($dependencies as $dependency) {
233                    if (!isset($alreadyRegistered[$dependency])) {
234                        $alreadyRegistered[$dependency] = $dependency;
235                        $this->app->register($dependency);
236                    }
237                }
238            }
239        }
240        //$this->app->bind(CsrfTokenProvider::class, CsrfTokenContextBuilder::class);
241        TagMap::register($this->app, CsrfTokenContextBuilder::class, ['apie.core.context_builder']);
242        $this->app->tag(CsrfTokenContextBuilder::class, ['apie.core.context_builder']);
243
244        // this has to be added after CsrfTokenContextBuilder!
245        $this->app->bind(SessionContextBuilder::class);
246        TagMap::register($this->app, SessionContextBuilder::class, ['apie.core.context_builder']);
247        $this->app->tag(SessionContextBuilder::class, ['apie.core.context_builder']);
248
249        TagMap::register($this->app, RegisterBoundedContextActionContextBuilder::class, ['apie.core.context_builder']);
250        $this->app->tag(RegisterBoundedContextActionContextBuilder::class, ['apie.core.context_builder']);
251        $this->app->extend('config', function (Repository $config) {
252            $this->sanitizeConfig($config);
253            return $config;
254        });
255
256        TagMap::register($this->app, BackgroundProcessPersistListener::class, ['kernel.event_subscriber']);
257    }
258
259    private function sanitizeConfig(Repository $config): void
260    {
261        $rawConfig = $config->get('apie');
262        $path = storage_path('framework/cache/apie-config' . md5(json_encode($rawConfig)) . '.php');
263        $resources = [
264            new ReflectionClassResource(new \ReflectionClass(LaravelConfiguration::class)),
265            new ReflectionClassResource(new \ReflectionClass(static::class)),
266        ];
267        $configCache = new ConfigCache($path, true);
268        if ($configCache->isFresh()) {
269            $processedConfig = require $path;
270        } else {
271            $configuration = new LaravelConfiguration();
272
273            $processor = new Processor();
274
275            $processedConfig = $processor->processConfiguration($configuration, ['apie' => $rawConfig]);
276
277            if (!isset($processedConfig['scan_bounded_contexts'])) {
278                $processedConfig['scan_bounded_contexts'] = [];
279            }
280            if (empty($processedConfig['storage'])) {
281                $processedConfig['storage'] = null;
282            }
283            $code = '<?php' . PHP_EOL . 'return ' . var_export($processedConfig, true) . ';';
284            $configCache->write($code, $resources);
285        }
286
287        $config->set('apie', $processedConfig);
288    }
289}